/*
 * Copyright (c) 2010 Peter Hayes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.envconfig.util;

import java.util.HashSet;
import java.util.Set;

/**
 * Implements a hierarchy of configuration settings so that keys can
 * be overriden.
 *
 * @author Pete Hayes
 */
public class ResolvingConfiguration extends AbstractConfiguration {

    public static final String START_DELIM = "${";
    public static final String END_DELIM = "}";
    // List of underlying configurations in descending order of precedence
    private Configuration configuration;

    /**
     * Create a new instance of this class
     *
     * @param configurations The list of configuration objects in descending
     * order of precedence
     */
    public ResolvingConfiguration(Configuration configuration) {
        if (configuration == null) {
            throw new IllegalArgumentException("Configuration must "
                    + "not be null");
        }

        this.configuration = configuration;
    }

    @Override
    public Set<String> keys() {
        Set<String> keys = configuration.keys();

        // resolve all keys
        Set<String> resolvedKeys = new HashSet<String>();
        for (String key : keys) {
            resolvedKeys.add(resolve(key, new HashSet<String>()));
        }

        return resolvedKeys;
    }

    @Override
    public String get(String key, String def) {
        return get(key, def, new HashSet<String>());
    }

    private String get(String key, String def, HashSet<String> resolving) {
        // Resolve any variables in the key
        key = resolve(key, resolving);

        // Lookup value
        String value = configuration.get(key, def);

        // if not null, resolve
        if (value != null) {
            return resolve(value, resolving);
        } else {
            return null;
        }
    }

    /*
     * This method looks for ${<key>} patterns within a value and attempts
     * to replace that with a configuration value.  If it can't resolve a
     * value, it throws an IllegalArgumentException.  If it hits an infinite
     * loop, it will throw an IllegalArgumentException.
     */
    private String resolve(String s, HashSet<String> resolving) {
        if (s == null) {
            return null;
        }

        if (!resolving.add(s)) {
            throw new IllegalArgumentException("Infinite recursion detected " +
                    "resolving " + s);
        }

        StringBuffer sb = null;
        
        int startIndex = 0;
        int currIndex = -1;
        
        while ((currIndex = s.indexOf(START_DELIM, ++currIndex)) >= 0) {
            int count = 1;
            
            for (int endIndex = currIndex + START_DELIM.length(); endIndex < s.length(); endIndex++) {
                if (s.regionMatches(endIndex, START_DELIM, 0, START_DELIM.length())) {
                    count++;
                } else if (s.regionMatches(endIndex, END_DELIM, 0, END_DELIM.length())) {
                    count--;
                    
                    if (count == 0) {
                        String key = s.substring(currIndex + START_DELIM.length(), endIndex);
                        
                        String value = get(key, null, resolving);
                        
                        if (value == null) {
                            throw new IllegalArgumentException("Could not resolve " +
                                    key + " within " + s);
                        }
                        
                        if (sb == null) {
                            sb = new StringBuffer();
                        }
                        
                        sb.append(s.substring(startIndex, currIndex));
                        
                        sb.append(value);
                        
                        startIndex = endIndex + END_DELIM.length();
                    }
                    
                    currIndex = endIndex;
                    
                    break; // break out of the loop now
                }
            }
        }
        
        if (sb != null) {
            s = sb.append(s.substring(startIndex)).toString();
        }

        resolving.remove(s);

        return s;
    }
}